package com.qding.park.manager.web.controller;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.qding.park.common.core.annotation.log.OperationLogType;
import com.qding.park.common.core.annotation.log.SystemControllerLog;
import com.qding.park.common.core.exceptions.ExceptionMessage;
import com.qding.park.common.core.exceptions.auth.AuthException;
import com.qding.park.common.core.exceptions.system.SystemUnKnown;
import com.qding.park.common.utils.DateUtils;
import com.qding.park.common.utils.export.DataField;
import com.qding.park.common.utils.export.ExportDataSource;
import com.qding.park.common.utils.export.excel.ExcelDataExportor;
import com.qding.park.common.utils.export.excel.MODE;
import com.qding.park.common.web.controller.BaseController;
import com.qding.park.manager.common.pojo.ParkDataResult;
import com.qding.park.manager.common.rest.domain.AnswerMsg;
import com.qding.park.manager.common.rest.domain.AnswerMsgFactoryImpl;
import com.qding.park.manager.common.rest.enums.ResponseCodeEnum;
import com.qding.park.manager.facade.statis.service.CarStatisFacade;
import com.qding.park.manager.facade.statis.service.InoutcheckStatisFacade;
import com.qding.park.manager.pojo.PowerInfo;
import com.qding.park.manager.pojo.enums.CarOpSpecialEnum;
import com.qding.park.manager.pojo.enums.CarOpTypeEnum;
import com.qding.park.manager.pojo.enums.CarTypeEnum;
import com.qding.park.manager.pojo.enums.CardTypeEnum;
import com.qding.park.manager.pojo.enums.OrderSourceEnum;
import com.qding.park.manager.pojo.example.NcPresenExample;
import com.qding.park.manager.pojo.example.TbOutcheckExample;
import com.qding.park.manager.pojo.noncore.NcParkInoutInfo;
import com.qding.park.manager.web.conf.SystemConfig;
import com.qding.park.manager.web.form.InoutcheckManualReleaseForm;
import com.qding.park.manager.web.form.InoutcheckOutForm;
import com.qding.park.manager.web.form.InoutcheckPresenForm;
import com.qding.park.manager.web.power.Power;

/**
 * @ClassName: Web_InoutcheckController
 * @Description: 车辆进出场记录查询
 * @author Comsys-Administrator
 * @date 2016年10月9日 下午6:01:15
 *
 */
@RestController
@RequestMapping("/inoutcheck")
public class Web_InoutcheckController extends BaseController {

	private static final Logger _log = LoggerFactory.getLogger(Web_InoutcheckController.class);

	@Autowired
	private CarStatisFacade carStatisFacade;

	/**
	 * @Fields inoutcheckStatisFacade : TODO（车辆进出场记录统计）
	 */
	@Autowired
	private InoutcheckStatisFacade inoutcheckStatisFacade;

	/**
	 * @Description (TODO分页查询在场记录分页查询)
	 * @param form 查询表单
	 * @param result 
	 * @return
	 */
	@Power(visitPark = "#form.getParkId()")
	@SystemControllerLog(description = "车辆在场查询", operation = OperationLogType.inoutcheck_presen)
	@RequestMapping("/presen")
	public AnswerMsg presen(@Valid InoutcheckPresenForm form, BindingResult result) {
		/* 解析验证结果 */
		super.analysisValid(result);
		/* 解析验证结果 */
		PowerInfo power = this.getPowerInfo();
		NcPresenExample example = new NcPresenExample();
		if (!StringUtils.isBlank(form.getStartTime())) {
			// 进场开始时间
			example.setStartTime(DateUtils.parseDate(form.getStartTime(), DateUtils.DATE_FORMAT_DATETIME));
		}
		if (!StringUtils.isBlank(form.getEndTime())) {
			// 进场结束时间
			example.setEndTime(DateUtils.parseDate(form.getEndTime(), DateUtils.DATE_FORMAT_DATETIME));
		}
		if (!StringUtils.isBlank(form.getCarNum())) {
			// 车牌
			example.setCarNum(form.getCarNum());
		}
		if (!StringUtils.isBlank(form.getCardType())) {
			// 卡类型
			example.setCardType(Integer.valueOf(form.getCardType()));
		}
		if (!StringUtils.isBlank(form.getParkId())) {
			// 车场id
			example.setParkId(Integer.valueOf(form.getParkId()));
		}
		if (!StringUtils.isBlank(form.getCarType())) {
			// 车场id
			example.setCarType(Integer.valueOf(form.getCarType()));
		}
		if (!power.isAdminIs()) {
			example.setInParks(power.getParkList());
		}

		example.setFileDomain(SystemConfig.getFileDomain());
		ParkDataResult dataResult = inoutcheckStatisFacade.presen(example, Integer.valueOf(form.getJumpPage()),
				Integer.valueOf(form.getPageLength()));
		AnswerMsg answerMsg = AnswerMsgFactoryImpl.createAnswerMsg(dataResult.getData());
		return answerMsg;
	}
	
	
	
	/**
	 * @Description (TODO手动放行记录 分页查询)
	 * @param form
	 * @param result
	 * @return
	 */
	@Power(visitPark = "#form.getParkId()")
	@SystemControllerLog(description = "手动放行查询", operation = OperationLogType.inoutcheck_presen)
	@RequestMapping("/manualRelease")
	public AnswerMsg manualRelease(@Valid InoutcheckManualReleaseForm form, BindingResult result) {
		/* 解析验证结果 */
		super.analysisValid(result);
		/* 解析验证结果 */
		PowerInfo power = this.getPowerInfo();
		
		long total =Integer.valueOf(form.getPageLength());
		List dataList = new ArrayList();
		for (int i=0;i<total;i++) {
//			Map<String, Object> map = new HashMap<String, Object>();
//			map.put("allowType", 2);
//			map.put("channel", "");
//			map.put("channelType", 2);
//			map.put("operator", "雷阳");
//			map.put("picture", "");
//			map.put("portName", "岗停1");
//			map.put("releaseTime", new Date().getTime()/1000);
//			dataList.add(map);
		}
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("list", dataList);
		data.put("currentPage", Integer.valueOf(form.getJumpPage()));
		data.put("numPerPage", Integer.valueOf(form.getPageLength()));
		data.put("totalCount", total);
		data.put("hast", Integer.valueOf(form.getJumpPage()) > 1 ? true : false);
		data.put("next", Integer.valueOf(form.getPageLength()) * Integer.valueOf(form.getJumpPage()) < total ? true : false);

		ParkDataResult parkDataResult = ParkDataResult.createObjDate();
		parkDataResult.putMapOnObj(data);
		
		AnswerMsg answerMsg = AnswerMsgFactoryImpl.createAnswerMsg(parkDataResult.getData());
		return answerMsg;
	}

	/**
	 * @Description (TODO这分页出场)
	 * @param form
	 * @param result
	 * @return
	 */
	@Power(visitPark = "#form.getParkId()")
	@SystemControllerLog(description = "车辆出场查询", operation = OperationLogType.inoutcheck_out)
	@RequestMapping("/out")
	public AnswerMsg out(@Valid InoutcheckOutForm form, BindingResult result) {
		/* 解析验证结果 */
		super.analysisValid(result);
		/* 解析验证结果 */

		PowerInfo power = this.getPowerInfo();

		// NcInoutcheckExample
		TbOutcheckExample example = new TbOutcheckExample();
		if (!StringUtils.isBlank(form.getStartTime())) {
			// 进场开始时间
			example.setStartTime(DateUtils.parseDate(form.getStartTime(), DateUtils.DATE_FORMAT_DATETIME));
		}
		if (!StringUtils.isBlank(form.getEndTime())) {
			// 进场结束时间
			example.setEndTime(DateUtils.parseDate(form.getEndTime(), DateUtils.DATE_FORMAT_DATETIME));
		}
		if (!StringUtils.isBlank(form.getCarNum())) {
			// 车牌
			example.setCarNum(form.getCarNum());
		}
		if (!StringUtils.isBlank(form.getCardType())) {
			// 卡类型
			example.setCardType(form.getCardType());
		}
		if (!StringUtils.isBlank(form.getOpType())) {
			// 放行类型
			example.setOpType(form.getOpType());
		}

		if (!StringUtils.isBlank(form.getParkId())) {
			// 车场id
			example.setParkId(form.getParkId());
		}

		if (!StringUtils.isBlank(form.getParkingTime())) {
			// 在场时间
			example.setParkingTime(form.getParkingTime());
		}
		if (!StringUtils.isBlank(form.getParkingFee())) {
			// 费用
			example.setParkingFee(form.getParkingFee());
		}

		if (!power.isAdminIs()) {
			example.setInParks(power.getParkList());
		}

		example.setFileDomain(SystemConfig.getFileDomain());
		ParkDataResult dataResult = inoutcheckStatisFacade.out(example, Integer.valueOf(form.getJumpPage()),
				Integer.valueOf(form.getPageLength()));
		AnswerMsg answerMsg = AnswerMsgFactoryImpl.createAnswerMsg(dataResult.getData());
		return answerMsg;

	}

	/**
	 * @param startTime
	 *            出场的开始时间
	 * @param endTime
	 *            出场结束时间
	 * @param parkId
	 *            车场编号
	 * @return
	 */
	@SystemControllerLog(description = "车辆出场导出", operation = OperationLogType.inoutcheck_out)
	@RequestMapping("/out_exportExcel")
	@ResponseBody
	public AnswerMsg out_exportExcel(final String startTime, final String endTime, final String parkId) {

		try {
			final PowerInfo power = this.getPowerInfo();
			if (!StringUtils.isBlank(parkId) && !power.getParkList().contains(Integer.valueOf(parkId))
					&& !power.isAdminIs()) {
				throw new AuthException(AuthException.TypeEnum.EXCEPTION_AUTH.getId(), null,
						ExceptionMessage.createExceptionMessage(AuthException.TypeEnum.EXCEPTION_AUTH.getDesc(),
								this.getUsername() + " 没有此车场的权限", "权限不足:"));
			}
			final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
			String filename = "出场记录报表_" + sdf2.format(new Date());
			response.setHeader("Content-disposition",
					"attachment; filename=" + URLEncoder.encode(filename + ".xls", "utf-8"));
			OutputStream os = response.getOutputStream();
			DataField[] dataFields = new DataField[20];
			dataFields[0] = new DataField("车牌", "carNum", 10);
			dataFields[1] = new DataField("车辆类型", "cardType", 25);
			dataFields[2] = new DataField("进场岗停", "inPortName", 50);
			dataFields[3] = new DataField("进场时间", "inCheckTime", 25);
			dataFields[4] = new DataField("进场照片", "inCheckPhoto", 30);
			dataFields[5] = new DataField("出场岗亭", "outPortName", 20);
			dataFields[6] = new DataField("出场时间", "outCheckTime");
			dataFields[7] = new DataField("出场照片", "outCheckPhoto");
			dataFields[8] = new DataField("在场时间", "inParkTime", 30);
			dataFields[9] = new DataField("缴费时间", "payTime", 30);
			dataFields[10] = new DataField("缴费类型", "payType", 30);
			dataFields[11] = new DataField("缴费金额(元)", "parkingFee", 30);
			dataFields[12] = new DataField("应收金额(元)", "shouldFee", 30);
			dataFields[13] = new DataField("放行类型", "allowType", 30);
			dataFields[14] = new DataField("车牌属性", "carNumAttr", 30);
			dataFields[15] = new DataField("姓名", "memberName", 30);
			dataFields[16] = new DataField("手机", "tel", 30);
			dataFields[17] = new DataField("车辆类型", "carType", 10);
			dataFields[18] = new DataField("特殊处理", "opSpecial", 30);
			dataFields[19] = new DataField("操作员", "operator", 30);

			new ExcelDataExportor<Object>(dataFields, new ExportDataSource<Object>() {
				@Override
				public List getData() {
					// 查询统计条件
					
					TbOutcheckExample example = new TbOutcheckExample();
					if (!StringUtils.isBlank(startTime)) {
						// 进场开始时间
						example.setStartTime(DateUtils.parseDate(startTime, DateUtils.DATE_FORMAT_DATETIME));
					}
					if (!StringUtils.isBlank(endTime)) {
						// 进场结束时间
						example.setEndTime(DateUtils.parseDate(endTime, DateUtils.DATE_FORMAT_DATETIME));
					}
					if (!StringUtils.isBlank(parkId)) {
						// 车场编号
						example.setParkId(parkId);
					}
					if (!power.isAdminIs()) {
						example.setInParks(power.getParkList());
					}
					List<NcParkInoutInfo> ncList = inoutcheckStatisFacade.out_exportExcel(example);
					List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
					int temp = 0;
					for (int i = 0; i < ncList.size(); i++) {
						Map<String, Object> mapParam = new HashMap<String, Object>();
						NcParkInoutInfo info = ncList.get(i);
						temp = i;
						mapParam.put("carNum", info.getCarNum());
						mapParam.put("inPortName", info.getRoomName());
						mapParam.put("cardType", CardTypeEnum.getDescByType(info.getCardType()));
						mapParam.put("inCheckTime", info.getEnterTime() == null ? ""
								: DateUtils.formatDate(info.getEnterTime(), DateUtils.DATE_FORMAT_DATETIME));
						mapParam.put("inCheckPhoto", "");
						mapParam.put("outPortName", info.getOutRoomName());
						mapParam.put("outCheckTime", info.getOutTime() == null ? ""
								: DateUtils.formatDate(info.getOutTime(), DateUtils.DATE_FORMAT_DATETIME));
						mapParam.put("outCheckPhoto", "");
						mapParam.put("parkingFee", info.getFeeMoney()/100);
						mapParam.put("shouldFee", info.getShouldFeeMoney()/100);
						mapParam.put("carNumAttr", "");
						mapParam.put("inParkTime", DateUtils.getDatePoor(info.getOutTime(), info.getEnterTime()));
						mapParam.put("payType", OrderSourceEnum.getDescByCode(info.getOrderSource()));
						mapParam.put("allowType", CarOpTypeEnum.getDescByCode(info.getOpType()));
						
						mapParam.put("memberName", info.getMemberName());
						mapParam.put("tel", info.getTel());
						mapParam.put("carType", CarTypeEnum.fromInt(info.getCarType()));
						mapParam.put("opSpecial", CarOpSpecialEnum.getDescByCode(info.getOpSpecial()));
						mapParam.put("operator", info.getOperator());
						mapParam.put("payTime", info.getOutTime() == null ? ""
								: DateUtils.formatDate(info.getOutTime(), DateUtils.DATE_FORMAT_DATETIME));
						lists.add(mapParam);
					}
					return lists;
				}
			}, os, MODE.EXCEL).export();

			AnswerMsg answerMsg = AnswerMsgFactoryImpl.createAnswerMsg(null);
			return answerMsg;
		} catch (Exception e) {
			SystemUnKnown ex = new SystemUnKnown(e, ExceptionMessage.createExceptionMessage(SystemUnKnown.default_Name,
					"未知Exception", "payStartTime=" + startTime + ",payEndTime=" + endTime));
			exceptionHandle.handle(ex);
			AnswerMsg answerMsg = AnswerMsgFactoryImpl.createErrorAnserMsg(ResponseCodeEnum.SYSTEM_ERROR);
			return answerMsg;
		}
	}
}
